package com.imoblife.brainwavestus.util;

import java.io.IOException;
import java.util.HashMap;

import junit.framework.Assert;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitMapFlyweightFactory {

	private static HashMap<String, BitMapFlyweight> mBufferPoolHashMap;

	static {
		mBufferPoolHashMap = new HashMap<String, BitMapFlyweightFactory.BitMapFlyweight>();
	}

	private static AssetManager mAssetManager;

	public static class BitMapFlyweight {

		private Bitmap mBitmap;		
		private int instenceCount;
		private String mBitMapKey;

		protected BitMapFlyweight(String bitMapKey) {

			//Assert.assertNotNull(mAssetManager);
			try {
				mBitmap = BitmapFactory.decodeStream(mAssetManager.open("icon/"
						+ bitMapKey + ".icon"));
			} catch (IOException e) {

				e.printStackTrace();
			}
			//Assert.assertNotNull(mBitmap);
			mBitMapKey = bitMapKey;
			mBufferPoolHashMap.put(bitMapKey, this);

		}

		protected int getInstenceCount() {
			return instenceCount;
		}


		protected void setInstenceCount(int instenceCount) {
			this.instenceCount = instenceCount;
		}


		public boolean release() {

			//Assert.assertNotNull(mBitmap);

			if (--instenceCount == -1) {
				
				if(mBitmap != null){
					
					mBitmap.recycle();
				}
				
				if(mBufferPoolHashMap != null) {
					
					mBufferPoolHashMap.remove(mBitMapKey);
				}
				return true;
			} else {
			
			}

			return false;

		}


		public Bitmap getBitmap() {
			return mBitmap;
		}

	}


	public BitMapFlyweight getBitMapFlyweight(String bitmapName) {

		//Assert.assertNotNull("requestRelease", bitmapName);
		BitMapFlyweight bitMapFlyweight = mBufferPoolHashMap.get(bitmapName);
		if (bitMapFlyweight != null) {
			bitMapFlyweight
					.setInstenceCount(bitMapFlyweight.getInstenceCount() + 1);
			
		} else {
			bitMapFlyweight = new BitMapFlyweight(bitmapName);
		}

		return bitMapFlyweight;

	}

	public boolean requestRelease(String bitmapName) {

		//Assert.assertNotNull("requestRelease", bitmapName);

		BitMapFlyweight bitMapFlyweight = mBufferPoolHashMap.get(bitmapName);

		if (bitMapFlyweight != null && bitMapFlyweight.release()) {
			return true;
		}
		return false;
	}


	public int getBufferPoolSize() {


		return mBufferPoolHashMap.size();
	}

	private static BitMapFlyweightFactory bitMapFlyweightFactory;// ȫ��Ψһ��ʵ��


	public static BitMapFlyweightFactory getBitMapFlyweightFactory(
			AssetManager assetManager) {
		mAssetManager = assetManager;

		if (bitMapFlyweightFactory == null) {
			bitMapFlyweightFactory = new BitMapFlyweightFactory();
		}

		return bitMapFlyweightFactory;
	}

	protected BitMapFlyweightFactory() {

	}

}
